package com.wyj.classloader;

import com.wyj.server.Digester;
import com.wyj.server.Wrapper;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * TODO: WebAppFileProcessor 应用程序文件处理类
 *
 * @author wuyijie
 * @date 2021/12/16 11:39 上午
 */
public class WebAppFileProcessor {
    private ClassLoader classLoader;
    private String webAppName;

    public WebAppFileProcessor(ClassLoader classLoader, String webAppName) {
        this.classLoader = classLoader;
        this.webAppName = webAppName;
    }


    public ClassLoader getClassLoader() {
        return classLoader;
    }

    public String getWebAppName() {
        return webAppName;
    }

    /**
     * TODO: 主要处理方法
     *
     * @author wuyijie
     * @date 2021/12/16 11:40 上午
     */
    public void process(Map<String, Wrapper> stringWrapperMap) {
        URL webAppUrl = Digester.class.getResource("/webApps" + "/" + this.webAppName);
        if (null != webAppUrl) {
            //得到相应的应用程序文件对象
            File webAppFile = new File(webAppUrl.getPath());

            // this.processLibDirectoryFile(webAppFile);
            // this.processClassesDirectoryFile(webAppFile);
            this.processXmlFile(webAppFile, stringWrapperMap);
        }else {
            throw new RuntimeException("process 失败了啊啊啊啊啊啊");
        }
    }

    // public void processClassesDirectoryFile(File webAppFile) {
    //     File classesDirectoryFile = getSpecificFile(webAppFile, "classes", true);
    //
    // }
    //
    // public void processLibDirectoryFile(File webAppFile) {
    //     File libDirectoryFile = getSpecificFile(webAppFile, "lib", true);
    //
    // }

    public void processXmlFile(File webAppFile, Map<String, Wrapper> stringWrapperMap) {
        File webXmlFile = getSpecificFile(webAppFile, "web.xml", false);
        doProcessWebXml(webXmlFile, stringWrapperMap);
    }

    /**
     * TODO: 获取指定名称的文件（夹）对象
     *
     * @param file        需要进行查找、比对的文件（夹）
     * @param targetName  目标文件（夹）名称
     * @param isDirectory 目标文件（夹）是否是文件夹
     * @return java.io.File
     * @author wuyijie
     * @date 2021/12/16 11:11 上午
     */
    public File getSpecificFile(File file, String targetName, boolean isDirectory) {
        File specificFile=null;
        System.out.println(file.getName());
        boolean fileDirectory = file.isDirectory();
        if (isDirectory){
            if (fileDirectory){
                if (targetName.equals(file.getName())) {
                    specificFile= file;
                }else{
                    File[] files = file.listFiles();
                    if (null != files && files.length > 0) {
                        for (File childFile : files) {
                            if (childFile.isDirectory()) {
                                specificFile = getSpecificFile(childFile, targetName, isDirectory);
                            }
                        }
                    }
                }
            }
        }else{
            if (!fileDirectory){
                if (targetName.equals(file.getName())) {
                    specificFile= file;
                }
            }else{
                File[] files = file.listFiles();
                if (null != files && files.length > 0) {
                    for (File childFile : files) {
                        specificFile= getSpecificFile(childFile, targetName, isDirectory);
                    }
                }
            }
        }
        return specificFile;
    }


    /**
     * TODO: 解析web.xml文件对象，封装wrapper
     *
     * @param webXmlFile       web.xml文件对象
     * @param stringWrapperMap 结果封装
     * @author wuyijie
     * @date 2021/12/16 11:42 上午
     */
    private void doProcessWebXml(File webXmlFile, Map<String, Wrapper> stringWrapperMap) {
        try {
            InputStream resourceAsStream = new FileInputStream(webXmlFile);
            SAXReader saxReader = new SAXReader();
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> servletElementList = rootElement.elements("servlet");
            Map<String, Wrapper> earlyStringWrapperMap=new HashMap<>();
            //解析
            for (Element servletElement : servletElementList) {
                Element servletNameElement = servletElement.element("servlet-name");
                Element servletClassElement = servletElement.element("servlet-class");

                String servletName = servletNameElement.getTextTrim();
                String servletClass = servletClassElement.getTextTrim();
                Wrapper wrapper = new Wrapper(servletName, servletClass, null);
                earlyStringWrapperMap.put(servletName, wrapper);
            }

            // List<Node> servletMappingNodeList = rootElement.selectNodes("./servlet-mapping");
            List<Element> servletMappingElementList = rootElement.elements("servlet-mapping");

            for (Element servletMappingElement : servletMappingElementList) {
                Element servletNameElement = servletMappingElement.element("servlet-name");
                Element urlPatternNodeElement = servletMappingElement.element("url-pattern");

                String servletName = servletNameElement.getTextTrim();
                String urlPattern = urlPatternNodeElement.getTextTrim();
                if (earlyStringWrapperMap.containsKey(servletName)) {
                    earlyStringWrapperMap.get(servletName).setPattern(urlPattern);
                    stringWrapperMap.put(urlPattern,earlyStringWrapperMap.get(servletName));
                }
            }

        } catch (FileNotFoundException | DocumentException e) {
            e.printStackTrace();
        }

    }


}
